<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
    <% include ../partial/meta %>
    <link rel="stylesheet" href="/app/static/weixin/css/pure-min.css">
    <link rel="stylesheet" href="/app/static/weixin/css/weixin.css">
    <link rel="stylesheet" href="/app/static/weixin/css/zone-filter.css">
    <link rel="stylesheet" href="/app/static/weixin/css/plugin.css">
    <link rel="stylesheet" href="/app/static/weixin/css/nouislider.css">
    <style>
    	html, body {
    		height: 100%;
    		width: 100%;
    		background: #F0F0F0;
    	}
    </style>
</head>
<body>
	<header class="header">
		<p>房妈妈</p>
	</header>
	<footer class="footer">
		<div class="pure-g">
            <div class="pure-u-1-2">
            	<img src="/app/static/weixin/img/logo.png" alt="logo">
            	<span>
            		房妈妈合租<br>
            		住一块，更有趣
            	</span>
            </div>
            <div class="pure-u-1-2">
            	<a href="http://a.app.qq.com/o/simple.jsp?pkgname=com.fangmm.housemother">
            		下载房妈妈App
            	</a>
            </div>
        </div>
	</footer>
   	<div class="carousel-item">
   		<div class ="search-bar">
   			<img src="/app/static/weixin/img/search.png" alt="search">
   			<span>|</span>
   			请输入您的目标商圈或小区名
   			<span class="search-item">找合租房</span>
   		</div>
   		<div class="carousel">
   			<%
				for(var i = 0; i < add.ads.length; i++) {
   			%>
   			<a href="<%= add.ads[i].jumpUrl %>">
   				<img data-title ="" src="<%= add.ads[i].picture %>?h=192&q=60" alt="index">
   			</a>
   			<%
				}
   			%>
   		</div>
   	</div>
   	<div class="placeholder">
   		<!-- placeholder for scroll -->
   	</div>
   	<div class="filter-bar">
   		<div class="pure-g">
   		    <div class="pure-u-1-3 whitespace nowrap" name="zone"><img src="/app/static/weixin/img/area.png" alt="zone"><span >区域</span></div>
   		    <div class="pure-u-1-3 whitespace nowrap" name="filter"><img src="/app/static/weixin/img/screen-out.png" alt="filter"><span >筛选</span></div>
   		    <div class="pure-u-1-3 whitespace nowrap" name="sort"><img src="/app/static/weixin/img/sequencer.png" alt="sort"><span >排序</span></div>
   		</div>
   	</div>
   	<div class="dropload-item">
   		<div class="content">
   		    <div class="lists">
   		    	
   		    </div>
   		</div>
   	</div>
</body>
<script src="/app/static/weixin/js/zepto.min.js"></script>
<script src="/app/static/weixin/js/pubsub.js"></script>
<script src="/app/static/weixin/js/path.js"></script>
<script src="/app/static/weixin/js/localStorage.js"></script>
<script src="/app/static/weixin/js/carousel.js"></script>
<script src="/app/static/weixin/js/template.js"></script>
<script src="/app/static/weixin/js/zoneFilter.js"></script>
<script src="/app/static/weixin/js/dropload.js"></script>
<script src="/app/static/weixin/js/nouislider.js"></script>
<script id="item" type="text/html">
{{each houses as house i}}
<a href="/lists/{{house.house.houseId}}">
	<div class="pure-g">
	    <div class="pure-u-1 brand-color home-like">
	    	<img src="{{house.house.cover}}?q=60&w=424" alt="pic">
	    	<div><img src="/app/static/weixin/img/home_like.png" alt="pic">{{house.favoriteNum}}</div>
	    	
	    	<span class="home-rent">
	    		¥{{house.house.singleRentFloor}}间<small>起</small>
	    	</span>
	    </div>
	    <div class="pure-u-1 main-descption">
	    	<p class="whitespace nowrap">{{house.house.community}}</p>

	    	<p class="whitespace nowrap">{{house.house.region}} - {{house.house.roomNum}}室{{house.house.hallNum}}厅{{house.house.toiletNum}}卫 - {{house.house.area}}㎡ | 入住时间：{{house.house.checkinTime}}</p>
	    	
	    	<p class="whitespace nowrap">
	    	{{if house.house.check }}
	    		<span class="check-for">验</span>
	    	{{/if }}
	    	<span class="come-from">来源</span><span class="come-to">{{house.house.from}}</span>
	    	</p>
	    </div>
	    {{if house.house.limits}}
	    	{{each house.house.limits as limit}}
	    		{{if limit.code == 1}}

	    		{{else}}
	    			<div class="pure-u-1 chief-list">
	    				<div class="pure-g">
	    					{{if house.house.teamNum > 0}}
	    				    <div class="pure-u-2-3">
	    				    	<span>室长<img class="icon" src="/app/static/weixin/img/intro.png" ></span>
	    				    	{{each house.teams as team i}}
	    				    		{{if i < 4}}
	    				    			<img class="profile" src="{{team.leaderAvatar}}" alt="profile">
	    				    		{{/if }}
	    				    	{{/each}}
	    				    </div>
	    				    <div class="pure-u-1-3 text-small text-right">{{house.house.teamNum}}个室长在招募</div>
	    				    {{else }}
	    				    	<div class="pure-u-3-3">
	    				    		<span>室长<img class="icon" src="/app/static/weixin/img/intro.png" ></span>
	    				    		<span> 暂无室友小组，快来招募你的室友小组吧！</span>
	    				    	</div>
	    				    {{/if }}
	    				</div>
	    			</div>
	    		{{/if}}
	    	{{/each}}
	    {{else}}
	    	<div class="pure-u-1 chief-list">
	    		<div class="pure-g">
	    			{{if house.house.teamNum > 0}}
	    		    <div class="pure-u-2-3">
	    		    	<span>室长<img class="icon" src="/app/static/weixin/img/intro.png" ></span>
	    		    	{{each house.teams as team i}}
	    		    		{{if i < 4}}
	    		    			<img class="profile" src="{{team.leaderAvatar}}" alt="profile">
	    		    		{{/if }}
	    		    	{{/each}}
	    		    </div>
	    		    <div class="pure-u-1-3 text-small text-right">{{house.house.teamNum}}个室长在招募</div>
	    		    {{else }}
	    		    	<div class="pure-u-3-3">
	    		    		<span>室长<img class="icon" src="/app/static/weixin/img/intro.png" ></span>
	    		    		<span> 暂无室友小组，快来招募你的室友小组吧！</span>
	    		    	</div>
	    		    {{/if }}
	    		</div>
	    	</div>
    	{{/if}}
	    
	</div>
</a>
{{/each}}
</script>
<script>
	$(function() {
		var Cache = new WebStorageCache({
			storage: 'localStorage',
			exp: Infinity
		});

		const api_host = "http://api.fangmm.com/v3";
		var util = (function() {
			return {
				getZone: function(url, callback) {
					$.get(url, function(data) {
						if(0 == data.code) {
							callback(data)
						} else {
							console.log(data.msg)
						}
					}, 'json')
				},
				serialize: function(params) {
					var array = [];
					for (var p in params) {
					    array.push(p + '=' + params[p]);
					}
					return array.join('&');
				}

			}
		})();
		util.getZone(api_host + '/settings/cities/3502', function(data) {
			new zoneFilter(data);
		});
		new screenFilter();
		new sortFilter();

		// carousel
		(function(){
			var carouselEntity    = $('.carousel');
			carouselEntity.carousel({
				isShowPager:    false,
				slideCallback:  function(index) {
				    
				}
			})
		})();

		function renderItem(data) {
			var html = template('item', data);
			return html
		}
		
		(function(){
			// filter
			var $body				= $('html');
			var $win				= $(window);
			var $placeholder		= $('.placeholder');
			var $filterBar			= $('.filter-bar');
			var dropCon				= $('.dropload-item .content');
			var listCon				= $('.dropload-item .lists');
			var zoneItem			= $('[name="zone"]'),
			    filterItem			= $('[name="filter"]'),
			    sortItem			= $('[name="sort"]');
			var mapFilter			= [
				{item: zoneItem, class: 'zone'},
				{item: filterItem, class: 'filter'},
				{item: sortItem, class: 'sort'}
			];
			var params              = {
				app: 'm',
				cityCode: 3502,
				regionCode: '',
				order: '',
				rent: '',
				roomNum: '',
				page: 1,
				pageSize: 5
			}
			var texts = ['', '', ''];
			var selfProxy           = null;

			window.hasSession = function(key) {
			    return sessionStorage.getItem(key) ? true : false
			}
			window.saveSession = function(key, value) {
			    sessionStorage.setItem(key, JSON.stringify(value))
			}
			window.getSession = function(key) {
			    return JSON.parse(sessionStorage.getItem(key))
			}

			if(hasSession('data')) {
				params = getSession('data');
			}
			if(hasSession('texts')) {
				texts = getSession('texts');
				mapFilter.forEach(function(item, i) {
					mapFilter[i].item.find('span').text(texts[i]);
				})
			}


			// refresh
			dropCon.dropload({
			    scrollArea : window,
			    loadDownFn : function(self){
			    	selfProxy = self;
			        $.ajax({
			            type: 'GET',
			            url: api_host + '/houses/app?' + util.serialize(params),
			            dataType: 'json',
			            success: function(data){
			            	params.page++;
			            	if(0 == data.code) {
			            		if(data.houses.length > 0) {
			            			var items = renderItem(data);
			            			listCon.append(items);
			            			self.resetload();
			            		} else {
			            			self.lock();
			            			self.noData();
			            			self.resetload();
			            		}
			            		
			            	} else {
			            		console.log('Ajax error!');
			                	self.resetload();
			            	}
			            },
			            error: function(xhr, type){
			               	console.log('Ajax error!');
			                self.resetload();
			            }
			        });
			    }
			});

			var renderFilter = function(msg, data){
				for (var key in data) {
					if(params.hasOwnProperty(key)) {
						params[key] = data[key];
					}
				}

				saveSession('data', params);

				// reset dropload list
				listCon.empty();
				params.page = 1;

				// reset dropload set
				if(selfProxy != null) {
					selfProxy.insert = false;
					selfProxy.unlock();
					selfProxy.fnAutoLoad(selfProxy);
				}
			    mapFilter[msg].item.find('span').text(data.name);
			    texts[msg] = data.name;
			    saveSession('texts', texts);
			};
			PubSub.subscribe( '0', renderFilter );
			PubSub.subscribe( '1', renderFilter );
			PubSub.subscribe( '2', renderFilter );

			for( var i = 0; i < mapFilter.length; i++) {
				(function(i){
					mapFilter[i].item.on('click', function(event) {
						$body.addClass(mapFilter[i].class)
					});
				})(i)
			}

			$win.on('scroll', function(event) {
				if($win.scrollTop() > 200) {
					$filterBar.addClass('fixed');
					$placeholder.addClass('fixed');
				} else {
					$filterBar.removeClass('fixed');
					$placeholder.removeClass('fixed');
				}
			});

		})();
		
		(function(){
			var $body         = $('html'),
			 	$goSearchItem = $('.search-bar'),
			 	cancel		  = '.ui-searchbar-cancel',
			 	button		  = '.search-menu',
			 	search		  = '.search',
			 	mainSearch	  = '.main-search',
			 	searchHis	  = '.search-history',
			 	searchList	  = '.search-list',
			 	listCon		  = '.search-list .content',
			 	itemCon		  = '.search-list .lists',
			 	itemHis		  = '.history-item',
			 	clear	  	  = '.clear',
			 	keyword	  	  = '',
			 	selfProxy	  = null,
			 	url			  = '',
			 	params        = {
			 		app: 'user',
			 		cityCode: 3502,
			 		page: 1,
			 		pageSize: 5
			 	}
			 	tpl           = [
			'<div class ="main-search">',
				'<div class="search-page">',
						'<div class="ui-searchbar-wrap ui-border-b focus">',
			         	'<div class="ui-searchbar ui-border-radius">',
			             	'<img class="ui-icon-search" src="/app/static/weixin/img/search.png" alt="search">',
			             	'<div class="ui-searchbar-input"><input autofocus="autofocus" class="search-menu" value="" type="text" placeholder="请输入您的目标商圈或小区名" autocapitalize="off"><span class="search">搜索</span></div>',
			         	'</div>',
			         	'<span class="ui-searchbar-cancel">取消</span>',
			     	'</div>',
				'</div>',
			'</div>'
			].join('');

			var hisTpl 		 = [
				'<div class="search-history">',
					'<div class="pure-g">',
					    '<div class="pure-u-1-2">搜索历史</div>',
					    '<div class="pure-u-1-2 clear">清空</div>',
					    '{{each list as value i}}',
					        '<div class="pure-u-1 history-item"><img src="/app/static/weixin/img/location.png" alt="">{{value}}</div>',
					    '{{/each}}',
					'</div>',
				'</div>',
			].join('');


			Path.map("/").to(function(){
			    $body.removeClass('search');
			    
			});
			Path.map("/search").to(function(){
				$body.addClass('search')
				if($(mainSearch).length == 0) {
			    	$body.append(tpl)
				}
				if($(searchHis).length == 0) {
			    	getHistory()
				}

			    function getHistory() {
			    	var data = Cache.get('fangmm');
			    	if(!data) {
			    		Cache.set('fangmm', []);
			    		data = Cache.get('fangmm');
			    	}
			    	if(data.length != 0) {
			    		var render = template.compile(hisTpl);
			    		var html = render({list: data});
			    		var hisCon = $(mainSearch);
			    		hisCon.append(html);
			    	}
			    }

			});

			Path.history.listen(true); 
			function goSearch() {
				Path.history.pushState({}, '搜索', '/search');
				$body.find(button).focus();
			}
			function goIndex() {
				Path.history.pushState({}, '房妈妈', '/');
				$(searchList).find('*').off();
				$(searchList).remove();
			}

			function searchVal(event, val) {
				if(val) {
					keyword = val;
				} else {
					if(event.keyCode == 13) {
						keyword = $(this).val();
						if('' == keyword) {
							return
						}
					} else {
						return
					}
				}
			
				var cache = Cache.get('fangmm');
				if(cache.indexOf(keyword) < 0) {

					if(cache.length  == 5) {
						cache.shift() 
					}
					cache.push(keyword);
					Cache.set('fangmm', cache);
				}
				params.page = 1;

				if($(listCon).length == 0) {
					var $itemCon = $(searchHis);
					$itemCon.find('*').off();
					$itemCon.remove();
					initDrop();
				} else {
					$(searchList).find('.lists').empty();
					selfProxy.insert = false;
					selfProxy.unlock();
					selfProxy.fnAutoLoad(selfProxy)
				}
			}

			function initDrop() {
				var tpl = [
					'<div class ="search-list">',
						'<div class="content">',
						    '<div class="lists">',
						   	'</div>',
						'</div>',
					'</div>'
				].join('');
				var $mainContain = $(mainSearch);
				$mainContain.append(tpl);

				var $dropCon = $(listCon);
				var $listCon = $(itemCon);
				$dropCon.dropload({
				    container: $('.main-search'),
				    loadDownFn : function(self){
				    	selfProxy = self;
				        $.ajax({
				            type: 'GET',
				            url: api_host + '/houses/app?' + util.serialize(params) +'&keyword='+ keyword,
				            dataType: 'json',
				            success: function(data){
				            	params.page++;
				            	if(0 == data.code) {
				            		if(data.houses.length > 0) {
				            			var items = renderItem(data);
				            			$listCon.append(items);
				            			self.resetload();
				            		} else {
				            			self.lock();
				            			self.noData();
				            			self.resetload();
				            		}
				            		
				            	} else {
				            		console.log('Ajax error!');
				                	self.resetload();
				            	}
				            },
				            error: function(xhr, type){
				                console.log('err');
				            }
				        });
				    }
				});
			}

			$goSearchItem.on('click', goSearch);
			$body.on('click', cancel, goIndex);
			$body.on('click', clear, function() {
				var $itemCon = $(searchHis);
				Cache.set('fangmm', []);
				$itemCon.find('*').off();
				$itemCon.remove();
			});
			$body.on('click', itemHis, function(event) {
				searchVal(event, $(this).text());
			});
			$body.on('keypress', button, searchVal);
			$body.on('click', search, function(event) {
				searchVal(event, $(button).val());
			});
			
			

		})()

	})
</script>
<% include ../partial/analyse %>
</html>
